import acm.program.*;
import acm.graphics.*;
import java.awt.event.*;

public class BasicTetris extends GraphicsProgram {
	
	// How long to pause between each heartbeat
	private static final int HEARTBEAT_MS = 200;

	// The size of a grid square, in pixels
	private static final int GRID_SIZE = 20;

	// The size of a "piece" in pixels
	private static final int PIECE_SIZE = 2 * GRID_SIZE;

    // An instance var to keep track of the active piece
    private GRect active = null;
    private MouseEvent lastClick = null;

	public void run() {
	    addMouseListeners();
		createPiece();
		while(true) {
		    // its ok if their heartbeat is at the end
		    pause(HEARTBEAT_MS);
		    
		    resolveLeftRight();
		    resolveDownward();
		}
	}
	
	public void mouseClicked(MouseEvent e) {
	    lastClick = e;
	}
	
	private void resolveLeftRight() {
	    if(lastClick != null) {
	        double middleX = active.getX() + GRID_SIZE;
	        if(lastClick.getX() < middleX) {
	            active.move(-GRID_SIZE, 0);
	        } else {
	            active.move(GRID_SIZE, 0);
	        }
	        lastClick = null;
	    }
	}
	
	private void resolveDownward() {
	    double xBelow = active.getX() + 0.5 * GRID_SIZE;
	    double yBelow = active.getY() + 2.5 * GRID_SIZE;
	    GObject c1 = getElementAt(xBelow, yBelow);
	    GObject c2 = getElementAt(xBelow + GRID_SIZE, yBelow);
	    if(c1 != null || c2 != null || yBelow > getHeight()) {
	        createPiece();
	    } else {
	        active.move(0, GRID_SIZE);
	    }
	}
	
	private void createPiece() {
	    active = new GRect(PIECE_SIZE, PIECE_SIZE);
	    active.setFilled(true);
	    int x = (getWidth() - PIECE_SIZE)/2;
	    add(active, x, 0);
	}

}